<template>
  <div class="system-config">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统配置管理</span>
          <el-button type="primary" :icon="Refresh" @click="refreshConfig">刷新配置</el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础配置 -->
        <el-tab-pane label="基础配置" name="basic">
          <el-form ref="basicFormRef" :model="basicConfig" :rules="basicRules" label-width="150px">
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="basicConfig.systemName" placeholder="请输入系统名称" style="width: 300px" />
            </el-form-item>
            <el-form-item label="系统版本" prop="systemVersion">
              <el-input v-model="basicConfig.systemVersion" placeholder="请输入系统版本" style="width: 300px" />
            </el-form-item>
            <el-form-item label="系统描述" prop="systemDescription">
              <el-input v-model="basicConfig.systemDescription" type="textarea" :rows="3" placeholder="请输入系统描述" style="width: 500px" />
            </el-form-item>
            <el-form-item label="系统Logo" prop="systemLogo">
              <el-upload
                class="logo-upload"
                :action="uploadAction"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
              >
                <img v-if="basicConfig.systemLogo" :src="basicConfig.systemLogo" class="logo-preview" />
                <el-icon v-else class="logo-upload-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="备案号" prop="icp">
              <el-input v-model="basicConfig.icp" placeholder="请输入备案号" style="width: 300px" />
            </el-form-item>
            <el-form-item label="版权信息" prop="copyright">
              <el-input v-model="basicConfig.copyright" placeholder="请输入版权信息" style="width: 500px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBasicConfig" :loading="saveLoading">保存配置</el-button>
              <el-button @click="resetBasicConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 邮件配置 -->
        <el-tab-pane label="邮件配置" name="email">
          <el-form ref="emailFormRef" :model="emailConfig" :rules="emailRules" label-width="150px">
            <el-form-item label="SMTP服务器" prop="smtpHost">
              <el-input v-model="emailConfig.smtpHost" placeholder="请输入SMTP服务器地址" style="width: 300px" />
            </el-form-item>
            <el-form-item label="SMTP端口" prop="smtpPort">
              <el-input-number v-model="emailConfig.smtpPort" :min="1" :max="65535" />
            </el-form-item>
            <el-form-item label="发件人邮箱" prop="fromEmail">
              <el-input v-model="emailConfig.fromEmail" placeholder="请输入发件人邮箱" style="width: 300px" />
            </el-form-item>
            <el-form-item label="发件人昵称" prop="fromName">
              <el-input v-model="emailConfig.fromName" placeholder="请输入发件人昵称" style="width: 300px" />
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="emailConfig.username" placeholder="请输入用户名" style="width: 300px" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="emailConfig.password" type="password" placeholder="请输入密码" style="width: 300px" show-password />
            </el-form-item>
            <el-form-item label="启用SSL" prop="sslEnabled">
              <el-switch v-model="emailConfig.sslEnabled" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveEmailConfig" :loading="saveLoading">保存配置</el-button>
              <el-button @click="testEmailConfig">测试连接</el-button>
              <el-button @click="resetEmailConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 存储配置 -->
        <el-tab-pane label="存储配置" name="storage">
          <el-form ref="storageFormRef" :model="storageConfig" :rules="storageRules" label-width="150px">
            <el-form-item label="存储类型" prop="storageType">
              <el-radio-group v-model="storageConfig.storageType">
                <el-radio value="local">本地存储</el-radio>
                <el-radio value="oss">阿里云OSS</el-radio>
                <el-radio value="cos">腾讯云COS</el-radio>
                <el-radio value="obs">华为云OBS</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 本地存储配置 -->
            <template v-if="storageConfig.storageType === 'local'">
              <el-form-item label="存储路径" prop="localPath">
                <el-input v-model="storageConfig.localPath" placeholder="请输入本地存储路径" style="width: 400px" />
              </el-form-item>
              <el-form-item label="访问域名" prop="localDomain">
                <el-input v-model="storageConfig.localDomain" placeholder="请输入访问域名" style="width: 400px" />
              </el-form-item>
            </template>

            <!-- 阿里云OSS配置 -->
            <template v-if="storageConfig.storageType === 'oss'">
              <el-form-item label="Endpoint" prop="ossEndpoint">
                <el-input v-model="storageConfig.ossEndpoint" placeholder="请输入OSS Endpoint" style="width: 400px" />
              </el-form-item>
              <el-form-item label="AccessKey" prop="ossAccessKey">
                <el-input v-model="storageConfig.ossAccessKey" placeholder="请输入AccessKey" style="width: 400px" />
              </el-form-item>
              <el-form-item label="SecretKey" prop="ossSecretKey">
                <el-input v-model="storageConfig.ossSecretKey" type="password" placeholder="请输入SecretKey" style="width: 400px" show-password />
              </el-form-item>
              <el-form-item label="Bucket" prop="ossBucket">
                <el-input v-model="storageConfig.ossBucket" placeholder="请输入Bucket名称" style="width: 400px" />
              </el-form-item>
            </template>

            <!-- 腾讯云COS配置 -->
            <template v-if="storageConfig.storageType === 'cos'">
              <el-form-item label="SecretId" prop="cosSecretId">
                <el-input v-model="storageConfig.cosSecretId" placeholder="请输入SecretId" style="width: 400px" />
              </el-form-item>
              <el-form-item label="SecretKey" prop="cosSecretKey">
                <el-input v-model="storageConfig.cosSecretKey" type="password" placeholder="请输入SecretKey" style="width: 400px" show-password />
              </el-form-item>
              <el-form-item label="Bucket" prop="cosBucket">
                <el-input v-model="storageConfig.cosBucket" placeholder="请输入Bucket名称" style="width: 400px" />
              </el-form-item>
              <el-form-item label="区域" prop="cosRegion">
                <el-input v-model="storageConfig.cosRegion" placeholder="请输入区域" style="width: 400px" />
              </el-form-item>
            </template>

            <!-- 华为云OBS配置 -->
            <template v-if="storageConfig.storageType === 'obs'">
              <el-form-item label="Endpoint" prop="obsEndpoint">
                <el-input v-model="storageConfig.obsEndpoint" placeholder="请输入OBS Endpoint" style="width: 400px" />
              </el-form-item>
              <el-form-item label="AccessKey" prop="obsAccessKey">
                <el-input v-model="storageConfig.obsAccessKey" placeholder="请输入AccessKey" style="width: 400px" />
              </el-form-item>
              <el-form-item label="SecretKey" prop="obsSecretKey">
                <el-input v-model="storageConfig.obsSecretKey" type="password" placeholder="请输入SecretKey" style="width: 400px" show-password />
              </el-form-item>
              <el-form-item label="Bucket" prop="obsBucket">
                <el-input v-model="storageConfig.obsBucket" placeholder="请输入Bucket名称" style="width: 400px" />
              </el-form-item>
            </template>

            <el-form-item>
              <el-button type="primary" @click="saveStorageConfig" :loading="saveLoading">保存配置</el-button>
              <el-button @click="resetStorageConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 安全配置 -->
        <el-tab-pane label="安全配置" name="security">
          <el-form ref="securityFormRef" :model="securityConfig" :rules="securityRules" label-width="150px">
            <el-form-item label="登录重试次数" prop="maxLoginAttempts">
              <el-input-number v-model="securityConfig.maxLoginAttempts" :min="1" :max="10" />
              <span class="form-tip">连续登录失败多少次后锁定账号</span>
            </el-form-item>
            <el-form-item label="锁定时间(分钟)" prop="lockDuration">
              <el-input-number v-model="securityConfig.lockDuration" :min="1" :max="1440" />
              <span class="form-tip">账号锁定时间，单位分钟</span>
            </el-form-item>
            <el-form-item label="密码最小长度" prop="minPasswordLength">
              <el-input-number v-model="securityConfig.minPasswordLength" :min="6" :max="32" />
            </el-form-item>
            <el-form-item label="密码复杂度" prop="passwordComplexity">
              <el-checkbox-group v-model="securityConfig.passwordComplexity">
                <el-checkbox value="uppercase">包含大写字母</el-checkbox>
                <el-checkbox value="lowercase">包含小写字母</el-checkbox>
                <el-checkbox value="number">包含数字</el-checkbox>
                <el-checkbox value="special">包含特殊字符</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="会话超时时间(分钟)" prop="sessionTimeout">
              <el-input-number v-model="securityConfig.sessionTimeout" :min="5" :max="1440" />
            </el-form-item>
            <el-form-item label="JWT过期时间(小时)" prop="jwtExpiration">
              <el-input-number v-model="securityConfig.jwtExpiration" :min="1" :max="168" />
            </el-form-item>
            <el-form-item label="启用双因子认证" prop="enable2FA">
              <el-switch v-model="securityConfig.enable2FA" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveSecurityConfig" :loading="saveLoading">保存配置</el-button>
              <el-button @click="resetSecurityConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'

// 当前激活的标签页
const activeTab = ref('basic')
const saveLoading = ref(false)
const uploadAction = '/api/upload/logo' // 上传Logo的API地址

// 基础配置
const basicConfig = ref({
  systemName: 'Zenith Mind 管理系统',
  systemVersion: '1.0.0',
  systemDescription: '现代化的企业级管理系统，提供用户管理、权限管理、数据字典等核心功能',
  systemLogo: '',
  icp: '',
  copyright: '© 2024 Zenith Mind. All rights reserved.'
})

const basicRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  systemVersion: [
    { required: true, message: '请输入系统版本', trigger: 'blur' },
    { pattern: /^\d+\.\d+\.\d+$/, message: '版本号格式不正确，如：1.0.0', trigger: 'blur' }
  ],
  systemDescription: [
    { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
  ],
  icp: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ],
  copyright: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 邮件配置
const emailConfig = ref({
  smtpHost: 'smtp.gmail.com',
  smtpPort: 587,
  fromEmail: '',
  fromName: 'Zenith Mind 系统',
  username: '',
  password: '',
  sslEnabled: true
})

const emailRules = {
  smtpHost: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口范围 1-65535', trigger: 'blur' }
  ],
  fromEmail: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 存储配置
const storageConfig = ref({
  storageType: 'local',
  localPath: '/uploads',
  localDomain: 'http://localhost:8080',
  ossEndpoint: '',
  ossAccessKey: '',
  ossSecretKey: '',
  ossBucket: '',
  cosSecretId: '',
  cosSecretKey: '',
  cosBucket: '',
  cosRegion: '',
  obsEndpoint: '',
  obsAccessKey: '',
  obsSecretKey: '',
  obsBucket: ''
})

const storageRules = {
  storageType: [
    { required: true, message: '请选择存储类型', trigger: 'change' }
  ],
  localPath: [
    { required: true, message: '请输入存储路径', trigger: 'blur' }
  ],
  localDomain: [
    { required: true, message: '请输入访问域名', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ]
}

// 安全配置
const securityConfig = ref({
  maxLoginAttempts: 5,
  lockDuration: 30,
  minPasswordLength: 8,
  passwordComplexity: ['uppercase', 'lowercase', 'number', 'special'],
  sessionTimeout: 30,
  jwtExpiration: 24,
  enable2FA: false
})

const securityRules = {
  maxLoginAttempts: [
    { required: true, message: '请输入登录重试次数', trigger: 'blur' }
  ],
  lockDuration: [
    { required: true, message: '请输入锁定时间', trigger: 'blur' }
  ],
  minPasswordLength: [
    { required: true, message: '请输入密码最小长度', trigger: 'blur' }
  ],
  sessionTimeout: [
    { required: true, message: '请输入会话超时时间', trigger: 'blur' }
  ],
  jwtExpiration: [
    { required: true, message: '请输入JWT过期时间', trigger: 'blur' }
  ]
}

// 表单引用
const basicFormRef = ref()
const emailFormRef = ref()
const storageFormRef = ref()
const securityFormRef = ref()

// 模拟配置数据
const mockConfigs = {
  basic: {
    systemName: 'Zenith Mind 管理系统',
    systemVersion: '1.0.0',
    systemDescription: '现代化的企业级管理系统',
    systemLogo: '',
    icp: '京ICP备12345678号',
    copyright: '© 2024 Zenith Mind. All rights reserved.'
  },
  email: {
    smtpHost: 'smtp.gmail.com',
    smtpPort: 587,
    fromEmail: 'noreply@zenithmind.com',
    fromName: 'Zenith Mind 系统',
    username: 'noreply@zenithmind.com',
    password: 'your-app-password',
    sslEnabled: true
  },
  storage: {
    storageType: 'local',
    localPath: '/uploads',
    localDomain: 'http://localhost:8080'
  },
  security: {
    maxLoginAttempts: 5,
    lockDuration: 30,
    minPasswordLength: 8,
    passwordComplexity: ['uppercase', 'lowercase', 'number', 'special'],
    sessionTimeout: 30,
    jwtExpiration: 24,
    enable2FA: false
  }
}

// 加载配置
const loadConfig = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    basicConfig.value = { ...mockConfigs.basic }
    emailConfig.value = { ...mockConfigs.email }
    storageConfig.value = { ...mockConfigs.storage }
    securityConfig.value = { ...mockConfigs.security }
    
    ElMessage.success('配置加载成功')
  } catch (error) {
    ElMessage.error('配置加载失败')
    console.error('Failed to load config:', error)
  }
}

// 保存基础配置
const saveBasicConfig = async () => {
  try {
    await basicFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('基础配置保存成功')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('基础配置保存失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 保存邮件配置
const saveEmailConfig = async () => {
  try {
    await emailFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('邮件配置保存成功')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('邮件配置保存失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 测试邮件配置
const testEmailConfig = async () => {
  try {
    await emailFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('邮件配置测试成功')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('邮件配置测试失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 保存存储配置
const saveStorageConfig = async () => {
  try {
    await storageFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('存储配置保存成功')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('存储配置保存失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 保存安全配置
const saveSecurityConfig = async () => {
  try {
    await securityFormRef.value.validate()
    saveLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('安全配置保存成功')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('安全配置保存失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 重置配置
const resetBasicConfig = () => {
  basicConfig.value = { ...mockConfigs.basic }
  basicFormRef.value?.resetFields()
}

const resetEmailConfig = () => {
  emailConfig.value = { ...mockConfigs.email }
  emailFormRef.value?.resetFields()
}

const resetStorageConfig = () => {
  storageConfig.value = { ...mockConfigs.storage }
  storageFormRef.value?.resetFields()
}

const resetSecurityConfig = () => {
  securityConfig.value = { ...mockConfigs.security }
  securityFormRef.value?.resetFields()
}

// 刷新配置
const refreshConfig = () => {
  loadConfig()
}

// Logo上传相关
const handleLogoSuccess = (response) => {
  if (response.code === 200) {
    basicConfig.value.systemLogo = response.data.url
    ElMessage.success('Logo上传成功')
  } else {
    ElMessage.error(response.message || 'Logo上传失败')
  }
}

const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过 2MB!')
    return false
  }
  return true
}

// 初始化加载
onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.system-config {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.logo-upload:hover {
  border-color: #409eff;
}

.logo-preview {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.logo-upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

@media (max-width: 768px) {
  .system-config {
    padding: 10px;
  }
  
  :deep(.el-form-item__label) {
    width: 100px !important;
  }
  
  :deep(.el-form-item__content) {
    margin-left: 100px !important;
  }
}
</style>